#!/usr/local/bin/python3

from __future__ import with_statement

from os.path import join
from extractor import *
from problem import *
from serve import *

def main(id, letters, ejudge_id):
    import os, tempfile
    dst_dir = tempfile.mkdtemp(dir=config.temp_dir_prefix)
    print("Write temporary to directory %s " % dst_dir)

    contest_xml = request_contest_xml(id)

    ejudge_dir = join(config.ejudge_dir, ejudge_id)
    serve_file = join(ejudge_dir, "conf", "serve.cfg")
    serve = Serve(serve_file)

    for id, name, url in extract_problems(contest_xml):
        id = id.upper() #contest xml use lowercase letters, while ejudge and web interface use uppercase
        if letters == None or id in letters:
            download_problem(dst_dir, id, url)
            prob_dir = join(dst_dir, id)
            meta, paths = extract_problem_meta(prob_dir)
            meta["id"] = id
            if name is not None:
                meta["short_name"] = '"' + name + '"'
            meta["super"] = config.abstract_problem

            install_problem(dst_dir, ejudge_dir, meta, paths)#can update meta information
            serve.update_problem(meta)


    import shutil
    shutil.copyfile(serve_file, join(dst_dir, "serve.cfg"))
    serve.store(serve_file)

    statements_file = download_statement(dst_dir,
            contest_xml, lang = config.language)
    ejudge_statements_dir = join(ejudge_dir, "statements")

    from os.path import exists, basename
    from os import makedirs
    from shutil import move, copy, copytree

    if statements_file != None:
        if not exists(ejudge_statements_dir):
            makedirs(ejudge_statements_dir)
        shutil.copyfile(statements_file,
            join(ejudge_statements_dir, basename(statements_file)))
    else:
        print("!!NO STATEMENT FOR CONTEST GENERATED!!")


if __name__ == "__main__":
    import sys
    if len(sys.argv) == 4:
        main(sys.argv[2], sys.argv[3], sys.argv[1])
    elif len(sys.argv) == 3:
        main(sys.argv[2], None, sys.argv[1])
    else:
        raise Exception(
                "usage:\n\tejudge_contest_id contest_id [problem_letters]")

